package com.android.job.service.request;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import com.android.job.exception.NotEnouchSpaceException;
import com.android.job.exception.SDNotEnouchSpaceException;
import com.android.job.exception.SDUnavailableException;
import com.android.job.fusion.FusionCode;
import com.android.job.model.DownloadItem;
import com.android.job.service.ConnectionTask;
import com.android.job.service.DownloadTask;
import com.android.job.service.IDownloadCallback;
import com.android.job.service.Request;
import com.android.job.util.CommonUtil;
import com.android.job.util.FileHelper;
import com.android.job.util.LogX;

public class DownloadFileRequest extends Request implements IDownloadCallback
{

	/**
	 * 下载的任务对象
	 */
	private DownloadItem item;

	private String infoReqUrl;

	/**
	 * 构造函数
	 */
	public DownloadFileRequest(DownloadItem item)
	{
		super(null, item.url);
		this.item = item;
	}

	/**
	 * 构造函数
	 */
	public DownloadFileRequest(String url)
	{
		super(url);
		infoReqUrl = url;

	}

	/**
	 * 构造函数
	 */
	public DownloadFileRequest(String url, int type)
	{
		super(url);
		setHttpType(type);
		infoReqUrl = url;

	}

	public void setItem(DownloadItem item)
	{
		this.item = item;
	}

	/**
	 * 设置断点  
	 */
	public void setBreakPointHeader(long start, long end)
	{
		StringBuffer breakPointStr = new StringBuffer("bytes=");
		breakPointStr.append(start);
		breakPointStr.append("-");
		breakPointStr.append(end);
		header.put("RANGE", breakPointStr.toString());
	}

	GetFileInfoRequest getUrlReq;

	public void initDownload(String fileInfo)
	{
		getUrlReq = new GetFileInfoRequest(this, infoReqUrl);
		getUrlReq.setFileInfo(fileInfo);
		getUrlReq.setHandler(handler);
		getUrlReq.getJSONResponse();
	}

	public void startDownload(String url)
	{
		httpRequestUrl = url;
		item.setTaskHandle(getJSONResponse());
		getUrlReq = null;
	}

	/**
	 * 发送请求
	 */
	protected ConnectionTask createConnectionTask()
	{
		// 构造网络层的下载链接任务
		ConnectionTask downloadTask = new DownloadTask(this, httpRequestUrl);

		// 获取文件大小设置下载断点
		//		long breakpoint = FileHelper.getLocalFileSize(item.savePath);

		//暂时不支持断点
		long breakpoint = 0;

		// 判断是否需要发送断点请求头
		if (breakpoint != 0 && breakpoint < item.fileSize)
		{
			downloadTask.setBreakPoint(breakpoint);
			setBreakPointHeader(breakpoint, item.fileSize);
		}
		else if (breakpoint != 0 && breakpoint >= item.fileSize)
		{
			FileHelper.deleteFile(item.savePath);
		}

		// 给任务初始化等待状态
		item.setStatus(FusionCode.DOWN_WAIT);
		//		item.setTask(downloadTask);

		//		item.savePath = FusionField.DOWNLOAD_PATH_SD + item.saveName;
		//item.fileDownTime = Util.getSystemTime();
		item.dateDistance = 0;
		return downloadTask;
	}

	/**
	 * 网络不可用处理
	 * @param code    状态码
	 * @param message 异常信息  
	 */
	public void onConnError(int code, String message)
	{

		if (this.handler != null)
		{
			handler.sendMessage(handler.obtainMessage(FusionCode.NETWORK_ERROR,
					fusionCode, 0, this.item));
		}
		clearRequest();
	}

	/**
	 * 超时处理
	 * @param code     状态码
	 * @param message  异常信息
	 */
	public void onTimeOut(int code, String message)
	{
		if (this.handler != null)
		{
			handler.sendMessage(handler.obtainMessage(
					FusionCode.NETWORK_TIMEOUT_ERROR, fusionCode, 0, this.item));

		}
		clearRequest();
	}

	/**
	 * 下载失败回调方法
	 * @param code      错误码
	 * @param message   错误信息  
	 */
	public void onError(int code, String message)
	{
		if (this.handler != null)
		{
			handler.sendMessage(handler.obtainMessage(code, fusionCode, 0,
					this.item));

		}
		clearRequest();
	}

	/**
	 * 取消下载回调处理
	 */
	public void canceledCallback()
	{
		clearRequest();
		//		if (this.handler != null)
		//		{
		//			handler.sendMessage(handler.obtainMessage(
		//					FusionCode.NETWORK_TIMEOUT_ERROR, fusionCode, 0, this.item));
		//
		//		}
	}

	/**
	 * 下载进度信息回调方法
	 * @param getLength      已下载的大小
	 * @param totalLength    需要下载的总大小
	 */
	public void onProgressChanged(long getLength, long totalLength)
	{
		item.fileSize = totalLength;
		item.downLen = getLength;
		if (item.getStatus() != FusionCode.DOWN_PROCESSING)
		{
			item.setStatus(FusionCode.DOWN_PROCESSING);
		}
		this.handler.sendMessage(handler.obtainMessage(
				FusionCode.DOWN_PROCESSING, item));

	}

	private void clearRequest()
	{
		item = new DownloadItem();
		item = null;
		if (connectTask != null)
		{
			super.cancelRequestTask();
		}
	}

	/**
	 * 下载暂停回调处理
	 */
	public void pausedCallback()
	{
		//		boolean isDownloading = item.isDownloading(); //false
		//		if (item.getTask() != null && isDownloading)
		//		{
		//			item.getTask().pausedConnect();
		//		}
		//		item.setStatus(FusionCode.DOWN_PAUSE);
		this.handler.sendMessage(handler.obtainMessage(FusionCode.DOWN_PAUSE,
				item));
		clearRequest();
	}

	/**
	 * 开始下载状态回调
	 */
	public void startDownloadCallback()
	{
	

		this.handler.sendMessage(handler.obtainMessage(
				FusionCode.DOWN_RECEIVE_MESSAGE, item));
	}

	public void successDownloadCallback()
	{
		
		if (this.handler != null)
		{
			this.handler.sendMessage(handler.obtainMessage(
					FusionCode.DOWN_SUCCESS, item));
		}
		clearRequest();
	}

	@Override
	protected void appendMainBody()
	{
		this.paramsters = new ArrayList<NameValuePair>();
		//		paramsters.add(new BasicNameValuePair("token", FusionField.HOTALK_SID));
		//		paramsters.add(new BasicNameValuePair("cname", FusionField.SN));
	}

	/**
	 * 创建下载文件目录
	 * @param fileLength 文件长度
	 */
	@Override
	public RandomAccessFile createFile(long fileLength)
	{
		//如果用户在运行过程中插入SD卡，则在此检查目录是否被创建
		CommonUtil.makeDir();
		//TODO
		File tempFile = null;
		RandomAccessFile file = null;
		try
		{
			String tempSavePath = item.savePath;
			String temp = tempSavePath.substring(0,
					tempSavePath.lastIndexOf("/") + 1);
			String filePath = FileHelper.selectFileSavaPath(fileLength, temp);
			tempFile = FileHelper.createDownloadFile(filePath, item.saveName);
			file = new RandomAccessFile(tempFile, "rw");
		}
		catch (IOException e)
		{
			LogX.trace("ConnectionTask:  ", e.getMessage());
		}
		catch (NotEnouchSpaceException e)
		{
			onError(FusionCode.LOW_MEMORY, "NotEnoughSpaceException");
			LogX.trace("ConnectionTask:  ", e.getMessage());
		}
		catch (SDUnavailableException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SDNotEnouchSpaceException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return file;
	}
}
